﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnterpriseFund.Common;
using DevExpress.Web.Mvc;
using System.Data;

namespace EnterpriseFund.Controllers
{
        [OutputCache(Duration = 0, VaryByParam = "none")]
    public class AllowanceIssueCheckController : AdminBaseController
    {
        //
        // GET: /AllowanceIssueCheck/
            [AuthorityActionFilter("m_AllowanceIssueCheck", Order = 1)]
            [LogPageActionFilter("补贴复核", Order = 2)]
        public ActionResult Index()
        {
            string y = OperateSession.get(GlobalConstant.PARAM_SYSYEAR);
            string strwhere = " (FStatus='1' or counts>0) and FYear='" + y + "'";
            List<Model.AllowanceIssue> AllowanceIssueList = new List<Model.AllowanceIssue>();
            AllowanceIssueList = GetAllowanceIssueListList(strwhere, 1);
            return View(AllowanceIssueList);
        }

        public ActionResult AllowanceIssueCheckEdit(string FIssueID)
        {
            BLL.AllowanceIssue allowanceIssueBLL = new BLL.AllowanceIssue();
            Model.AllowanceIssue allowanceIssueModel = new Model.AllowanceIssue();
            if (FIssueID != null && FIssueID != "")
            {
                allowanceIssueModel = allowanceIssueBLL.GetModel(FIssueID);
                BLL.VTaxAuditPolicyEval vtaxAuditPolicyEvalBLL = new BLL.VTaxAuditPolicyEval();
                DataTable dt = new DataTable();
                if (allowanceIssueModel.FStatus == "1")
                {
                    ViewData["showOpen"] = "true";
                }
                else
                {
                    ViewData["showOpen"] = "false";
                }
                //if (allowanceIssueModel.FStatus == "1")
                //{
                //    ViewData["type"] = "1";
                //    dt = vtaxAuditPolicyEvalBLL.GetAllowanceCalcManageList("FIssueID='" + FIssueID + "' and  (FStatus='1' or FStatus='-1') and evalFStatus ='3' ").Tables[0];
                //}
                //else if (allowanceIssueModel.FStatus == "0")
                //{
                //    ViewData["type"] = "1";
                //    dt = vtaxAuditPolicyEvalBLL.GetAllowanceCalcManageList("FIssueID='" + FIssueID + "' and  (FStatus='1' or FStatus='-1') and evalFStatus ='3' ").Tables[0];
                //}
                //else
                //{
                    ViewData["type"] = "2";
                    dt = vtaxAuditPolicyEvalBLL.GetAllowanceCalcManageList("FIssueID='" + FIssueID + "' and  (FStatus='2' or  FStatus='1' or FStatus='-1') and (evalFStatus ='3' or evalFStatus='-1') ").Tables[0];
                //}
               // DataTable dt = vtaxAuditPolicyEvalBLL.GetAllowanceCalcManageList("FIssueID='" + FIssueID + "' and  FStatus='1' and evalFStatus ='3' ").Tables[0];
                ViewData["showdata"] = GetEditTable(dt);
                ViewData["FIssueNo"] = allowanceIssueModel.FIssueNo;
                ViewData["FIssueID"] = allowanceIssueModel.FIssueID;
            }
            else
            {
                ViewData[""] = "请选择期号！";
            }
            return View("AllowanceIssueCheckEdit", allowanceIssueModel);
        }



        public string OpenToIssue(string fallowanceIssueEntryID, string FIssueID, string type, string EditType)
        {
            try
            {
                if (EditType == "js")
                {
                    BLL.TaxAuditPolicyEval taxAuditPolicyEvalBLL = new BLL.TaxAuditPolicyEval();
                    Model.AllowanceIssueEntry model = new Model.AllowanceIssueEntry();
                    model.FAllowanceIssueEntryID = decimal.Parse(fallowanceIssueEntryID);
                    model.FStatus = "2";
                    taxAuditPolicyEvalBLL.Check(model);
                }
                else
                {
                    BLL.SpecificAdjust specificAdjustBLL = new BLL.SpecificAdjust();
                    Model.SpecificAdjust model = new Model.SpecificAdjust();
                    model.FSpecificAdjustNo =fallowanceIssueEntryID;
                    model.FStatus = "2";
                    specificAdjustBLL.Check(model);
                }
                BLL.VTaxAuditPolicyEval vtaxAuditPolicyEvalBLL = new BLL.VTaxAuditPolicyEval();
                DataTable dt = new DataTable();

                if (type == "1")
                {
                    dt = vtaxAuditPolicyEvalBLL.GetAllowanceCalcManageList("FIssueID='" + FIssueID + "' and  FStatus='1' and evalFStatus ='3' ").Tables[0];
                }
                else
                {
                    dt = vtaxAuditPolicyEvalBLL.GetAllowanceCalcManageList("FIssueID='" + FIssueID + "' and  (FStatus='2' or  FStatus='1') and evalFStatus ='3' ").Tables[0];
                }
                
                dt = GetEditTable(dt);
                DataRow[] dr = dt.Select("cz='合计'");

                string s = "";
                if (dr.Count() > 0)
                {
                    s = "ok||" + dr[0]["se"] + "||" + dr[0]["FAllowanceAmount"] + "||" + dr[0]["YBTJE"] + "||" + dr[0]["BTJE"];
                }
                else
                {
                    return "ex";
                }

                return s;
            }
            catch
            {
                return "ex";
            }
        }

        public string IsReturn(string FIssueID)
        {
            BLL.AllowanceIssueEntry AllowanceIssueEntryBLL = new BLL.AllowanceIssueEntry();
            List<Model.AllowanceIssueEntry> list = AllowanceIssueEntryBLL.GetModelList(" FIssueID='" + FIssueID + "' and FAllowanceFileEntryID is not null");
            if (list.Count == 0)
            {
                return "ok";
            }
            else
            {
                return "no";
            }
        }

        public string ReturnToIssue(string fallowanceIssueEntryID, string FIssueID, string type, string EditType)
        {
            try
            {
                if (EditType == "js")
                {
                    BLL.AllowanceIssueEntry AllowanceIssueEntryBLL = new BLL.AllowanceIssueEntry();
                    Model.AllowanceIssueEntry AllowanceIssueEntryModel = AllowanceIssueEntryBLL.GetModel(decimal.Parse(fallowanceIssueEntryID));
                    if (AllowanceIssueEntryModel.FAllowanceFileEntryID != null && AllowanceIssueEntryModel.FAllowanceFileEntryID != "")
                    {
                        return "该数据已生成资金汇总表不可退回！";
                    }
                    BLL.TaxAuditPolicyEval taxAuditPolicyEvalBLL = new BLL.TaxAuditPolicyEval();
                    Model.AllowanceIssueEntry model = new Model.AllowanceIssueEntry();
                    model.FAllowanceIssueEntryID = decimal.Parse(fallowanceIssueEntryID);
                    model.FStatus = "0";
                    taxAuditPolicyEvalBLL.Check(model);
                }
                else
                {
                    BLL.SpecificAdjust specificAdjustBLL = new BLL.SpecificAdjust();
                    Model.SpecificAdjust SpecificAdjustModel = specificAdjustBLL.GetModel(fallowanceIssueEntryID);
                    if (SpecificAdjustModel.FAllowanceFileEntryID != null && SpecificAdjustModel.FAllowanceFileEntryID != "")
                    {
                        return "该数据已生成资金汇总表不可退回！";
                    }
                    Model.SpecificAdjust model = new Model.SpecificAdjust();
                    model.FSpecificAdjustNo = fallowanceIssueEntryID;
                    model.FStatus = "0";
                    specificAdjustBLL.Check(model);
                }

                BLL.VTaxAuditPolicyEval vtaxAuditPolicyEvalBLL = new BLL.VTaxAuditPolicyEval();
                DataTable dt = new DataTable();
                if (type == "1")
                {
                    dt = vtaxAuditPolicyEvalBLL.GetAllowanceCalcManageList("FIssueID='" + FIssueID + "' and  FStatus='1' and evalFStatus ='3' ").Tables[0];
                }
                else
                {
                    dt = vtaxAuditPolicyEvalBLL.GetAllowanceCalcManageList("FIssueID='" + FIssueID + "' and  (FStatus='2' or  FStatus='1') and evalFStatus ='3' ").Tables[0];
                }
                dt = GetEditTable(dt);
                DataRow[] dr = dt.Select("cz='合计'");

                string s = "";
                if (dr.Count() > 0)
                {
                    s = "ok||" + dr[0]["se"] + "||" + dr[0]["FAllowanceAmount"] + "||" + dr[0]["YBTJE"] + "||" + dr[0]["BTJE"];
                }
                else
                {
                    return "ex";
                }

                return s;
            }
            catch
            {
                return "ex";
            }
        } 

        #region  grid绑定

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.AllowanceIssue> GetAllowanceIssueListList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.AllowanceIssue AllowanceIssueBLL = new BLL.AllowanceIssue();
            string fiedls = "FIssueID";
            int total;
            DataSet ds = commonBll.GetListByPage("fund.v_AllowanceIssueCheckShow", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FIssueID", out total);
            List<Model.AllowanceIssue> AllowanceIssueList = AllowanceIssueBLL.DataTableToList(ds.Tables[0]);
            List<Model.AllowanceIssue> AllowanceIssueAllList = new List<Model.AllowanceIssue>();
            total = AllowanceIssueBLL.GetRecordCount2(strWhere);
            int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                AllowanceIssueAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (AllowanceIssueList.Count > i)
                {
                    AllowanceIssueAllList[((pageIndex - 1) * pageRowSize) + i] = AllowanceIssueList[i];
                }
            }

            return AllowanceIssueAllList;
        }

        public ActionResult AllowanceIssueCheckListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;

            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }

            string FStatus = Request.Params["FStatus"];
            string FIssueNo = Request.Params["FIssueNo"];

            string y = OperateSession.get(GlobalConstant.PARAM_SYSYEAR);

            string strwhere = "  FYear='" + y + "' ";

            if (FIssueNo != "")
            {
                strwhere += " and FIssueNo like '%" + FIssueNo + "%'";
            }

            if (FStatus != "")
            {
                if (FStatus == "2")
                {
                    strwhere += " and counts2 > 0";
                }
                else
                {
                    strwhere += "and ( FStatus='1' or counts>0) ";
                }
            }
            else
            {
                strwhere += "and  (FStatus='1' or counts>0)";
            }
            List<Model.AllowanceIssue> AllowanceIssueList = new List<Model.AllowanceIssue>();
            AllowanceIssueList = GetAllowanceIssueListList(strwhere, pageIndex);
            return PartialView("AllowanceIssueCheckListPartial", AllowanceIssueList);
        }

        #endregion  grid绑定

        public DataTable GetEditTable(DataTable dt)
        {
            dt.Columns.Add("cz");
            var q = (from nm in dt.AsEnumerable()
                     group nm by
                         new
                         {
                             t1 = nm.Field<decimal>("NSRDZDAH")
                         } into g
                     select new
                     {
                         NSRDZDAH = g.Key.t1
                     });
            foreach (DataRow drz in dt.Rows)
            {
                drz["YBTJE"] = decimal.Parse(drz["YBTJE"].ToString()) / 10000;
                if (drz["BTJE"] != null && drz["BTJE"].ToString() != "")
                {
                    drz["BTJE"] = decimal.Parse(drz["BTJE"].ToString()) / 10000;
                }
                drz["FAllowanceAmount"] = decimal.Parse(drz["FAllowanceAmount"].ToString()) / 10000;
                if (drz["FTaxAuditId"].ToString() == "-1")
                {
                    drz["FTaxClassAllowanceName"] = "特殊调整";
                }
            }
            
            dt.Columns["YBTJE"].DataType = typeof(decimal);
            dt.Columns["FAllowanceAmount"].DataType = typeof(decimal);
            dt.Columns["se"].DataType = typeof(decimal);

            

            //dt.Columns.Add("BTJE", typeof(decimal), "FAllowanceAmount-YBTJE");
            decimal sumse = dt.AsEnumerable().Sum(p => p.Field<decimal>("FAllowanceAmount"));
            decimal sumse2 = dt.AsEnumerable().Sum(p => p.Field<decimal>("YBTJE"));
            decimal? sumse3 = dt.AsEnumerable().Sum(p => p.Field<decimal?>("BTJE"));
            decimal sumse4 = dt.AsEnumerable().Sum(p => p.Field<decimal>("se"));

            DataRow dr = dt.NewRow();
            dr["cz"] = "合计";
            //dr["NSRBM"] = "合计";
            dr["FAllowanceAmount"] = sumse;
            dr["YBTJE"] = sumse2;
            dr["BTJE"] = sumse3;
            dr["se"] = sumse4;
            dr["NSRMC"] = "共" + q.Count() + "户";
            dr["FStatus"] = "9";
            dt.Rows.Add(dr);

            foreach (DataRow drz in dt.Rows)
            {
                drz["se"] = decimal.Round(decimal.Parse(drz["se"].ToString()),0);
                if (drz["FBaseAmount"] != null && drz["FBaseAmount"].ToString() != "")
                {
                    drz["FBaseAmount"] = decimal.Round(decimal.Parse(drz["FBaseAmount"].ToString()), 0);
                }
                if (drz["FInnerRate"] != null && drz["FInnerRate"].ToString() != "")
                {
                    drz["FInnerRate"] = decimal.Round(decimal.Parse(drz["FInnerRate"].ToString()) * 100, 2);
                }
                if (drz["FOuterRate"] != null && drz["FOuterRate"].ToString() != "")
                {
                    drz["FOuterRate"] = decimal.Round(decimal.Parse(drz["FOuterRate"].ToString()) * 100, 2);
                }
            }
            DataView dv = dt.DefaultView;
            dv.Sort = "FStatus Asc";
            return dv.ToTable();
        }

        public ActionResult LookEntry(string taxClassAllowanceNo, string FTaxAuditId)
        {
            BLL.TaxAuditAdjust taxAuditAdjustBLL = new BLL.TaxAuditAdjust();
            BLL.TaxAuditForm taxAuditFormBLL = new BLL.TaxAuditForm();
            BLL.TaxClassAllowance taxClassAllowanceBLL = new BLL.TaxClassAllowance();
            BLL.DJ_NSRXX DJ_NSRXXBLL = new BLL.DJ_NSRXX();
            DataSet ds = new DataSet();

            Model.TaxAuditForm tAM = taxAuditFormBLL.GetModel(FTaxAuditId);
            ViewData["nsrmc"] = tAM.NSRMC;
            ViewData["taxClassName"] = taxClassAllowanceBLL.GetModel(tAM.FYear, taxClassAllowanceNo).FTaxClassAllowanceName;
            ViewData["rq1"] = tAM.RKRQ_Q.ToString("yyyy-MM-dd");
            ViewData["rq2"] = tAM.RKRQ_Z.ToString("yyyy-MM-dd");
            ds = taxAuditAdjustBLL.GetListForPolicyEntry(FTaxAuditId, taxClassAllowanceNo);


            ds.Tables[0].Columns.Add("xh");
            int i = 1;
            foreach (DataRow r in ds.Tables[0].Rows)
            {
                r["xh"] = i;
                i++;
            }
            BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
            List<Model.TaxAuditLookEntry> taxAuditLookEntryList = new List<Model.TaxAuditLookEntry>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                Model.TaxAuditLookEntry tAE = new Model.TaxAuditLookEntry();
                tAE.se = decimal.Parse(dr["FAdjustAmount"].ToString());
                tAE.RKRQ = DateTime.Parse(dr["FAdjustDate"].ToString());
                tAE.isAdjust = dr["dataType"].ToString();
                tAE.AdjustNote = dr["FNote"].ToString();
                tAE.xh = int.Parse(dr["xh"].ToString());
                if (dr["FAdjustEmpNo"].ToString() != "")
                {
                    DataSet hrDs = hrEmplBLL.GetEmplFromViewByEmplNo(dr["FAdjustEmpNo"].ToString(), GlobalConstant.ENTITYNO);
                    if (hrDs.Tables[0].Rows.Count > 0)
                    {
                        tAE.AdjustName = hrDs.Tables[0].Rows[0]["FEmpName"].ToString();
                    }
                }
                taxAuditLookEntryList.Add(tAE);
            }

            OperateSession.addList<Model.TaxAuditLookEntry>("AllowanceIssueCheckList", taxAuditLookEntryList);
            return View(taxAuditLookEntryList);
        }

        public ActionResult LookEntryPartial()
        {
            return PartialView("LookEntryPartial", OperateSession.getList<Model.TaxAuditLookEntry>("AllowanceIssueCheckList").OrderBy(nm => nm.RKRQ));
        }

        public ActionResult CheckSave()
        {
            string checkNoALL = Fetch.Post("hidcheckNoALL");
            string type = Fetch.Post("hidSType");
            ViewData["SType"] = type;
            string id = Fetch.Post("hidFIssueID");
            try
            {
                switch (type)
                {
                    case "ALL":
                        {
                            BLL.AllowanceIssue AllowanceIssueBLL = new BLL.AllowanceIssue();
                            BLL.AllowanceIssueEntry AllowanceIssueEntryBLL = new BLL.AllowanceIssueEntry();
                            List<Model.AllowanceIssueEntry> list = AllowanceIssueEntryBLL.GetModelList("FIssueID='" + id + "' and FStatus<>2");
                           // List<Model.AllowanceIssueEntry> list = AllowanceIssueEntryBLL.GetModelList("FIssueID='" + id + "' and FStatus=0");
                            if (list.Count == 0)
                            {
                                Model.AllowanceIssue model = AllowanceIssueBLL.GetModel(id);
                                if (model.FStatus == "1")
                                {
                                    AllowanceIssueBLL.IssueAudit(id);
                                    WorkFlow("t_AllowanceIssue", "20", id, "open", "");
                                    ViewData["jsAlert"] = "操作成功";
                                }
                                else
                                {
                                    ViewData["jsAlert"] = "无法送该数据！";
                                }
                            }
                            else
                            {
                                ViewData["jsAlert"] = "还有" + list.Count + "条数据未处理或被退回";
                            }
                            break;
                        }
                    case "Portion":
                        {
                            BLL.AllowanceIssue AllowanceIssueBLL = new BLL.AllowanceIssue();
                            AllowanceIssueBLL.IssueAuditALL(checkNoALL);
                            ViewData["jsAlert"] = "操作成功";
                            break;
                        }
                }
            }
            catch(Exception ex)
            {
                ViewData["jsAlert"] = ex.Message;
            }
            return AllowanceIssueCheckEdit(id);
        }

    }
}
